package com.example.goodpet.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;

import com.example.goodpet.R;
import com.example.goodpet.bean.ResponseBody;
import com.example.goodpet.service.UserService;
import com.example.goodpet.utils.ActivityManager;
import com.example.goodpet.utils.Constants;
import com.example.goodpet.utils.SecurityUtils;
import com.example.goodpet.utils.RetrofitSingleton;
import com.example.goodpet.utils.UIUtils;
import com.hyphenate.chat.EMClient;
import com.hyphenate.easeui.utils.EaseEditTextUtils;
import com.hyphenate.exceptions.HyphenateException;
import com.zackratos.ultimatebarx.ultimatebarx.java.UltimateBarX;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class RegisterActivity extends FragmentActivity implements TextWatcher, View.OnClickListener, CompoundButton.OnCheckedChangeListener {
    String TAG=this.getClass().getSimpleName();
    //final
    public static final int VERIFICATION_STATE=100;

    //控件
    private EditText etPhone;
    private EditText etPwd;
    private EditText etPwdConfirm;
    private Button btnRegister;
    private CheckBox cbSelect;
    private TextView tvAgreement;
    //本地变量
    private String phone;
    private String pwd;
    private String pwdConfirm;
    private Drawable clear;
    private Drawable eyeOpen;
    private Drawable eyeClose;
    //网络请求
    private Retrofit retrofit;
    private UserService userService;
    private Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        UltimateBarX.statusBarOnly(this)
                .fitWindow(false)
                .light(true)
                .apply();
        ActivityManager.getInstance().addActivity(this);

        mContext=this;

        etPhone=findViewById(R.id.et_phone);
        etPwd=findViewById(R.id.et_pwd);
        etPwdConfirm=findViewById(R.id.et_pwd_confirm);
        btnRegister=findViewById(R.id.btn_register);
        cbSelect = findViewById(R.id.cb_select);
        tvAgreement = findViewById(R.id.tv_agreement);


        initListener();
        initData();

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        ActivityManager.getInstance().removeCurrent();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "onResume: "+this.getTaskId());
    }
    private void initData() {
        retrofit= RetrofitSingleton.getRetrofitNetConfig();
        userService=retrofit.create(UserService.class);

        tvAgreement.setText(getSpannable());
        tvAgreement.setMovementMethod(LinkMovementMethod.getInstance());

        eyeClose = getResources().getDrawable(R.drawable.d_pwd_hide);
        eyeOpen = getResources().getDrawable(R.drawable.d_pwd_show);
        clear = getResources().getDrawable(R.drawable.d_clear);
        EaseEditTextUtils.changePwdDrawableRight(etPwd, eyeClose, eyeOpen, null, null, null);
        EaseEditTextUtils.changePwdDrawableRight(etPwdConfirm, eyeClose, eyeOpen, null, null, null);
    }

    private void initListener() {

        etPhone.addTextChangedListener(this);
        etPwd.addTextChangedListener(this);
        etPwdConfirm.addTextChangedListener(this);
        btnRegister.setOnClickListener(this);
        cbSelect.setOnCheckedChangeListener(this);
        EaseEditTextUtils.clearEditTextListener(etPhone);
    }


    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        checkEditContent();
    }

    private void checkEditContent() {
        phone = etPhone.getText().toString().trim();
        pwd = etPwd.getText().toString().trim();
        pwdConfirm = etPwdConfirm.getText().toString().trim();
        EaseEditTextUtils.showRightDrawable(etPhone, clear);
        EaseEditTextUtils.showRightDrawable(etPwd, eyeClose);
        EaseEditTextUtils.showRightDrawable(etPwdConfirm, eyeClose);
        setButtonEnable(!TextUtils.isEmpty(phone) && !TextUtils.isEmpty(pwd) && !TextUtils.isEmpty(pwdConfirm) && phone.length()==11 && cbSelect.isChecked() );
    }
    private void setButtonEnable(boolean enable) {
        btnRegister.setEnabled(enable);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_register) {
            if (pwd.equals(pwdConfirm)) {
                pwd= SecurityUtils.MD5(pwd);
                startActivityForResult(new Intent(RegisterActivity.this, ShowVerificationActivity.class), VERIFICATION_STATE);
            }else {
                UIUtils.toast("两次密码不一致",false);
                etPwdConfirm.setText("");
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode==RESULT_OK){
            if (requestCode==VERIFICATION_STATE){
                userService.register(phone,pwd).enqueue(new Callback<ResponseBody<String>>() {
                    @Override
                    public void onResponse(Call<ResponseBody<String>> call, Response<ResponseBody<String>> response) {
                        ResponseBody<String> body = response.body();
                        if (body!=null){
                            int code = body.getCode();
                            if (code==200){
                                UIUtils.toast(body.getData(),false);
                                createIMUser();
                                ActivityManager.getInstance().removeCurrent();
                            }else if (code==300){
                                UIUtils.toast(body.getData(), false);
                                etPhone.setText("");
                                etPwd.setText("");
                                etPwdConfirm.setText("");
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseBody<String>> call, Throwable t) {

                    }
                });
            }
        }
    }
    private SpannableString getSpannable() {
        SpannableString spanStr = new SpannableString(getString(R.string.em_login_agreement));
        //设置下划线
        //spanStr.setSpan(new UnderlineSpan(), 3, 7, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        spanStr.setSpan(new MyClickableSpan() {
            @Override
            public void onClick(@NonNull View widget) {
                WebViewActivity.actionStart(mContext, Constants.BASE_URL_support+"/agreement.html");
            }
        }, 2, 7, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        //spanStr.setSpan(new UnderlineSpan(), 10, 14, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        spanStr.setSpan(new MyClickableSpan() {
            @Override
            public void onClick(@NonNull View widget) {
                WebViewActivity.actionStart(mContext, Constants.BASE_URL_support+"/privacy.html");
            }
        }, 8, spanStr.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return spanStr;
    }
    private void createIMUser(){

           new Thread(new Runnable() {
               @Override
               public void run() {
                   try {
                       EMClient.getInstance().createAccount(SecurityUtils.encryptPhoneNumber(phone),pwd);
                   } catch (HyphenateException e) {
                       e.printStackTrace();
                   }
               }
           }).start();

    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (buttonView.getId()==R.id.cb_select){
                setButtonEnable(!TextUtils.isEmpty(phone) && !TextUtils.isEmpty(pwd) && !TextUtils.isEmpty(pwdConfirm) && phone.length()==11  && isChecked);
        }
    }
    private abstract class MyClickableSpan extends ClickableSpan {

        @Override
        public void updateDrawState(@NonNull TextPaint ds) {
            super.updateDrawState(ds);
            ds.bgColor = Color.TRANSPARENT;
            ds.setColor(ContextCompat.getColor(mContext, R.color.white));
        }
    }
}